<!--
 * @Author: your name
 * @Date: 2021-03-15 20:53:56
 * @LastEditTime: 2021-03-15 20:56:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edi
 * @FilePath: \study\js\面试题\数组计算.html
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <body>
        <p>EventBus</p>
        <button id="box">点击</button>
        <button id="box1">点击1</button>
        <script>
            var Event = (function () {
                var list = {};
                var on = function (key, fn) {
                    if (!list[key]) {
                        list[key] = [];
                    }
                    list[key].push(fn);
                };

                var emit = function () {
                    // let key = [].shift.call(arguments, 1);
                    // arguments 中取出第一个参数
                    let key = Array.prototype.shift.call(arguments);
                    var fns = list[key];
                    if (!fns || fns.length == 0) return;
                    fns.forEach((cb) => {
                        cb(...arguments);
                    });
                };
                var off = function (key, fn) {
                    let fns = list[key];
                    if (!fns) return false;
                    if (!fn) {
                    } else {
                        for (let index = 0; index < fns.length; index++) {
                            const _fn = fns[index];
                            if (_fn == fn) {
                                fns.splice(index, 1);
                            }
                        }
                    }
                };

                return { list, on, emit, off };
            })();

            Event.on('ok', function (a) {
                console.log('ok 111', a);
            });
            Event.on('ok', function (a, b) {
                console.log('ok 222', a, b);
            });
            Event.on('ok', function (a, b, c) {
                console.log('ok 333', a, b, c);
            });

            var f1 = function () {
                console.log('f1()');
            };
            Event.on('fn-f1', f1);

            Event.emit('ok', 6);
            Event.emit('ok', 6, 7);
            Event.emit('ok', 6, 7, 8);
            console.log('----', Event.list);
            Event.emit('fn-f1');

            setTimeout(() => {
                Event.off('fn-f1');
                // Event.off('fn-f1', f1);
                console.log('====', Event.list);
                // Event.emit('fn-f1');
                Event.emit('fn-f1');
            }, 1000);
        </script>
    </body>
</html>
